package com.ruoyi.TaskForce.controller;


import com.ruoyi.TaskForce.domain.Team_Members;
import com.ruoyi.TaskForce.service.ITeamManagementService;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/FileTransfer")
public class FileTransferController {

    @Autowired
    private ITeamManagementService teamManagementService;

    // 定义上传文件的存储路径
    private static final String UPLOAD_DIR = "D:/uploads/";

    @PostMapping("/upload/{id}")
    public AjaxResult uploadFile(@PathVariable("id") Long id, @RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return AjaxResult.error("上传文件为空");
        }
        try {
            // 确保目录存在
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 生成随机文件名并保留原文件的扩展名
            String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String randomFileName = UUID.randomUUID().toString() + extension;

            // 目标文件路径
            String filePath = UPLOAD_DIR + randomFileName;

            // 保存文件到目标路径
            file.transferTo(new File(filePath));

            // 返回文件路径，供客户端访问
            String idCardImagePath = "/uploads/" + randomFileName;

            System.out.println("新的图片名字"+ idCardImagePath);
            teamManagementService.SaveImage( id, idCardImagePath);


            return AjaxResult.success("上传成功", idCardImagePath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("文件上传失败：" + e.getMessage());
        }
    }
}
